package cn.yshujia.service.impl;

import cn.yshujia.domain.entity.Classify;
import cn.yshujia.mapper.ClassifyMapper;
import cn.yshujia.repository.ClassifyRepository;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author YShuJia
 * @create 2024/4/23
 * @description 服务层
 */

@Service
public class ClassifyServiceImpl extends ServiceImpl<ClassifyMapper, Classify> implements IService<Classify> {
	
	@Resource
	public ClassifyMapper mapper;
	
	@Resource
	public ClassifyRepository repository;
	
	public Classify selectById(Long id) {
		return repository.selectById(id);
	}
	
	public List<Classify> getList() {
		return mapper.selectList(new LambdaQueryWrapper<Classify>()
				.orderByAsc(Classify::getPriority));
	}
	
	
	public List<Long> getIdsByType(Integer type) {
		List<Classify> list = mapper.selectList(new LambdaQueryWrapper<Classify>()
				.select(Classify::getId)
				.eq(Classify::getType, type));
		List<Long> ids = new ArrayList<>();
		if (!ObjectUtils.isEmpty(list)) {
			ids.addAll(list.stream().map(Classify::getId).toList());
		}
		return ids;
	}
	
	
	@Transactional (rollbackFor = {Exception.class})
	public Boolean insert(Classify classify) {
		List<Classify> list = mapper.selectList(new LambdaQueryWrapper<Classify>()
				.eq(Classify::getType, classify.getType())
				.orderByDesc(Classify::getId));
		if (!ObjectUtils.isEmpty(list)) {
			classify.setId(list.get(0).getId() + 1);
		} else {
			classify.setId(null);
		}
		int n = mapper.insert(classify);
		return n > 0;
	}
	
	@Transactional (rollbackFor = {Exception.class})
	public Boolean update(Classify classify) {
		int n = mapper.updateById(classify);
		return n > 0;
	}
	
	@Transactional (rollbackFor = {Exception.class})
	public Boolean remove(List<Long> ids) {
		int n = mapper.deleteByIds(ids);
		return n > 0;
	}
}
